package com.ttyec.park;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;

import com.ttyec.park.common.SharedPreferencesHelper;
import com.ttyec.park.fragments.BaseSetFragment;
import com.ttyec.park.fragments.HomeFragment;
import com.ttyec.park.fragments.UserInfoFragment;
import com.ttyec.park.service.SocketService;
import com.ttyec.park.websocket.AppResponseDispatcher;
import com.ttyec.park.websocket.CommonResponse;
import com.zhangke.websocket.AbsWebSocketActivity;
import com.zhangke.websocket.ErrorResponse;
import com.zhangke.websocket.Response;
import com.zhangke.websocket.WebSocketSetting;

public class homeActivity extends AbsWebSocketActivity implements NavigationView.OnNavigationItemSelectedListener {

    HomeFragment homeFragment;
    UserInfoFragment userInfoFragment;
    BaseSetFragment baseSetFragment;

    //本地储存方式
    private SharedPreferencesHelper sharedPreferencesHelper;

    private SocketService socketService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置本地储存方式
        sharedPreferencesHelper = new SharedPreferencesHelper(this);

        //隐藏虚拟键
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

        setContentView(R.layout.activity_home);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, null, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        initFragments();
        getSupportFragmentManager().beginTransaction().add(R.id.container, homeFragment).commit();
        initWsState();
    }

    private void initWsState() {
        SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
        String wsUrl = (String) helper.getSharedPreference(Utils.SP_WS_URL, "");
        if (!TextUtils.isEmpty(wsUrl)) {
            //配置 WebSocket，必须在 WebSocket 服务启动前设置
            WebSocketSetting.setConnectUrl(wsUrl);//必选
            WebSocketSetting.setResponseProcessDelivery(new AppResponseDispatcher());
            WebSocketSetting.setReconnectWithNetworkChanged(true);
            //启动 WebSocket 服务
//            startService(new Intent(this, WebSocketService.class));
            Intent intent = new Intent(this, SocketService.class);
            intent.putExtra("ip", (String) helper.getSharedPreference(Utils.SP_WS_HOST, ""));
            intent.putExtra("port", (String) helper.getSharedPreference(Utils.SP_WS_TOKEN, ""));
            bindService(intent, conn, Service.BIND_AUTO_CREATE);
            startService(new Intent(this, SocketService.class));
            getSupportFragmentManager().beginTransaction().replace(R.id.container, homeFragment).commit();
        } else {
            // 空，显示设置
            getSupportFragmentManager().beginTransaction().replace(R.id.container, baseSetFragment).commit();
        }
    }

    ServiceConnection conn = new ServiceConnection() {
        /**
         * 与服务器端交互的接口方法 绑定服务的时候被回调，在这个方法获取绑定Service传递过来的IBinder对象，
         * 通过这个IBinder对象，实现宿主和Service的交互。
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 获取Binder
            SocketService.MyBinder binder = (SocketService.MyBinder) service;
            socketService = binder.getService();
        }

        /**
         * 当取消绑定的时候被回调。但正常情况下是不被调用的，它的调用时机是当Service服务被意外销毁时，
         * 例如内存的资源不足时这个方法才被自动调用。
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
            socketService = null;
        }
    };

    //初始化fragment方法
    private void initFragments() {
        homeFragment = new HomeFragment();
        baseSetFragment = new BaseSetFragment();
        userInfoFragment = new UserInfoFragment();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.home) {
            getSupportFragmentManager().beginTransaction().replace(R.id.container, homeFragment).commit();
        } else if (id == R.id.baseset) {
            getSupportFragmentManager().beginTransaction().replace(R.id.container, baseSetFragment).commit();
        } else if (id == R.id.userinfo) {
            getSupportFragmentManager().beginTransaction().replace(R.id.container, userInfoFragment).commit();
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onMessageResponse(Response message) {
        int code = ((CommonResponse) message).getResponseEntity().getCode();
        switch (code) {
            case Utils.HANDLER_SET:
                baseSet(message);
                break;

        }
    }
    //-------------开始接收网络数据之后的业务处理---------------------------------------

    /**
     * 设置网络参数
     */
    private void baseSet(Response message) {
        String dataStr = ((CommonResponse) message).getResponseEntity().getData();
        if (dataStr != null && !dataStr.isEmpty()) {
            sharedPreferencesHelper.put(Utils.SP_BASESET, dataStr);
        }
        //开始启动网络摄像机
        //创建消息
        Message msg = Message.obtain();
        msg.what = Utils.HANDLER_START_NETWORK;
        msg.obj = dataStr;
    }

    //--------------结束网络数据-----------------------------------------------------
    @Override
    public void onSendMessageError(ErrorResponse errorResponse) {

    }

    @Override
    protected void onDestroy() {
        if (conn != null) {
            unbindService(conn);
        }
        stopService(new Intent(this, SocketService.class));
        super.onDestroy();
    }
}
